package com.zhangxun.controller;


import cn.hutool.core.io.FileUtil;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashSet;

@Api
@RefreshScope
@RestController
@RequestMapping("/admin/file")
public class FileController {

    //获取文件访问的IP地址
    @Value("${resources.url}")
    String url;

    @Autowired
    private FastFileStorageClient storageClient;


    @PreAuthorize("hasAuthority('prod:prod:save')")
    @ApiOperation("新增商品上传图片")
    @PostMapping("/upload/element")
    public ResponseEntity<String> upload(@RequestBody MultipartFile file) throws IOException {

        //获取文件后缀名
        String fileName = file.getOriginalFilename();
        String extName = FileUtil.extName(fileName);
        //上传图片获取路径
        StorePath path = storageClient.uploadFile(file.getInputStream(), file.getSize(), extName, new HashSet<>());
        //拼接完整的图片访问路径
        String imageUrl = url+path.getFullPath();

        System.out.println(imageUrl);
        //返回图片路径
        return ResponseEntity.ok(imageUrl);

    }
}
